﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using PropertyChanged;
using sys_Print.DataAsset;
using sys_Print.Models;
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System.Linq;
using System.Printing;
using System.Windows.Threading;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Shapes;

namespace sys_Print.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    public class DemoViewModel : ViewModelBase
    {
        [DoNotNotify]
        private readonly IFreeSql _fsql;
        [DoNotNotify]
        private PrintDialog PrintDialog = new PrintDialog();
        public PrintModel PrintModel { get; set; } = new PrintModel();

        public bool FirstIteration { get; set; }
        public bool IsBack { get; set; }
        public bool IsTowSided { get; set; }
        public int InsertionIndex { get; set; }
        public List<PrintModelType> PrintTypes { get; set; } = new List<PrintModelType>();
        public List<PrintCanvasModel> DataGrids { get; set; }
        public PrintCanvasModel SelectedDataGrid { get; set; }
        public ObservableCollection<PrintCanvasModel> PrintCanvasModels { get; set; } = new ObservableCollection<PrintCanvasModel>();
        public ObservableCollection<PrintCanvasModel> PrintBackCanvasModels { get; set; } = new ObservableCollection<PrintCanvasModel>();


        public RelayCommand DropDownOpenedCommand { get; private set; }
        public RelayCommand DropDownClosedCommand { get; private set; }
        public RelayCommand DataGridsDropDownOpenedCommand { get; private set; }
        public RelayCommand PrinterDropDownClosedCommand { get; private set; }
        public RelayCommand<TextBox> EnterKeyPressedSearchBar { get; private set; }
        public RelayCommand<DataGridRow> DataGridRowDeleteCommand { get; private set; }
        public RelayCommand<Meter> ListViewItemClickCommand { get; private set; }
        public RelayCommand AddDataGridButtonCommand { get; private set; }
        public RelayCommand<Button> PrintButtonCommand { get; private set; }
        public RelayCommand AllLeftButtonCommand { get; private set; }
        public RelayCommand LeftButtonCommand { get; private set; }
        public RelayCommand RightButtonCommand { get; private set; }
        public RelayCommand AllRightButtonCommand { get; private set; }
        public RelayCommand CheckedToggleButtonCommand { get; private set; }

        public DemoViewModel()
        {
            // 获取配置好的FreeSql实例
            _fsql = App.FsqlDB;

            //模板选择事件
            DropDownOpenedCommand = new RelayCommand(new Action(CommandDropDownOpened));
            DropDownClosedCommand = new RelayCommand(new Action(CommandDropDownClosed));
            AllLeftButtonCommand = new RelayCommand(new Action(CommandAllLeftButton));
            LeftButtonCommand = new RelayCommand(new Action(CommandLeftButton));
            RightButtonCommand = new RelayCommand(new Action(CommandRightButton));
            AllRightButtonCommand = new RelayCommand(new Action(CommandAllRightButton));
            DataGridsDropDownOpenedCommand = new RelayCommand(new Action(CommandDataGridsDropDownOpened));

            PrinterDropDownClosedCommand = new RelayCommand(new Action(CommandPrinterDropDownClosed));

            EnterKeyPressedSearchBar = new RelayCommand<TextBox>(new Action<TextBox>(SearchBarEnterKeyPressed));
            DataGridRowDeleteCommand = new RelayCommand<DataGridRow>(new Action<DataGridRow>(CommandDataGridRowDelete));

            ListViewItemClickCommand = new RelayCommand<Meter>(new Action<Meter>(CommandListViewItemClick));

            AddDataGridButtonCommand = new RelayCommand(new Action(AddDataGridButton));
            PrintButtonCommand = new RelayCommand<Button>(new Action<Button>(OnPrintButton));
            CheckedToggleButtonCommand = new RelayCommand(new Action(CheckedToggleButton));
        }

        private void CheckedToggleButton()
        {
            if (IsBack)
            {
                if (PrintBackCanvasModels.Count == 0)
                {
                    HandyControl.Controls.Growl.Warning("请先加载数据！");
                    IsBack = !IsBack;
                    return;
                }
                SelectedDataGrid = PrintBackCanvasModels.Where(x => x.ControlType == "DataGrid").First();
            }
            else
            {
                if (PrintCanvasModels.Count == 0)
                {
                    HandyControl.Controls.Growl.Warning("请先加载数据！");
                    IsBack = !IsBack;
                    return;
                }
                SelectedDataGrid = PrintCanvasModels.Where(x => x.ControlType == "DataGrid").First();
            }
            
            InsertionIndex = SelectedDataGrid.DataGridLists.Count;
        }

        private void CommandDataGridsDropDownOpened()
        {
            if (PrintModel.SelectedPrintType == null)
            {
                HandyControl.Controls.Growl.Info("请先加载模板！");
                return;
            }

            DataGrids = _fsql.Select<PrintCanvasModel>()
                            .Where(x => x.ModelId == PrintModel.SelectedPrintType.Id)
                            .Where(x => x.IsReverse == IsBack)
                            .Where(x => x.ControlType == "DataGrid")                            
                            .ToList();
        }

        /// <summary>
        /// 选中打印机
        /// </summary>
        private void CommandPrinterDropDownClosed()
        {
            PrintDialog.PrintQueue = PrintModel.SelectedPrinter;
        }

        /// <summary>
        /// 打印
        /// </summary>
        private void OnPrintButton(Button button)
        {
            if (PrintModel.Unprinteds == null || PrintModel.Unprinteds.Count == 0)
            {
                HandyControl.Controls.Growl.Warning("没有打印数据！");
                return;
            }

            if (PrintModel.SelectedPrinter == null)
            {
                HandyControl.Controls.Growl.Warning("请选择打印机！");
                return;
            }       

            if (PrintBackCanvasModels.Count == 0 && button.Tag.ToString() != "StrCanvas" && button.Tag.ToString() != "AllStrCanvas")
            {
                HandyControl.Controls.Growl.Warning("没有反面内容，请重新选择打印！");
                return;
            }

            // 获取要打印的 Border
            Border printBorder = new Border();
            if (button.Tag.ToString() != "BackCanvas" && button.Tag.ToString() != "AllBackCanvas")
            {
                printBorder = FindVisualChild<Border>(App.Current.MainWindow, "StrCanvas");
            }

            if (button.Tag.ToString() != "StrCanvas" && button.Tag.ToString() != "AllStrCanvas")
            {
                printBorder = FindVisualChild<Border>(App.Current.MainWindow, "BackCanvas");
            }

            ListView UnprintedsSelect = FindVisualChild<ListView>(App.Current.MainWindow, "Unprinted");

            ObservableCollection<Meter> meters = new ObservableCollection<Meter>();
            foreach (Meter item in UnprintedsSelect.SelectedItems)
            {
                meters.Add(item);
            }

            if(button.Tag.ToString().Contains("All"))
            {
                meters = PrintModel.Unprinteds;
            }

            PrintDialog = PrintModel.SelectedPrintType.GetPrintDialog(PrintDialog);
            
            for (int i = meters.Count - 1; i >= 0; i--)
            {
                //加载标定参数
                CommandListViewItemClick(meters[0]);

                //手动刷新 Canvas UI
                Application.Current.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() =>
                {
                    printBorder.UpdateLayout();
                }));

                if (button.Tag.ToString() != "StrCanvas" && button.Tag.ToString() != "AllStrCanvas")
                {
                    //创建一个FixedDocument
                    FixedDocument fixedDoc = new FixedDocument();
                    fixedDoc.DocumentPaginator.PageSize = new Size(printBorder.Width, printBorder.Height);

                    // 创建一个页面
                    PageContent pageContent = new PageContent();
                    fixedDoc.Pages.Add(pageContent);

                    // 创建一个FixedPage，并将其添加到页面中
                    FixedPage fixedPage = new FixedPage();
                    ((IAddChild)pageContent).AddChild(fixedPage);

                    // 创建一个VisualBrush，用于捕获Canvas的呈现
                    VisualBrush visualBrush = new VisualBrush(printBorder);
                    Rectangle rectangle = new Rectangle();
                    rectangle.Width = printBorder.Width;
                    rectangle.Height = printBorder.Height;
                    rectangle.Fill = visualBrush;

                    // 添加Rectangle到FixedPage
                    fixedPage.Children.Add(rectangle);

                    // 打印FixedDocument
                    PrintDialog.PrintDocument(fixedDoc.DocumentPaginator, "Printing Canvas");
                }                
                else {
                    PrintDialog.PrintVisual(printBorder, "Printing Canvas" + meters[0]);
                }

                //移动
                PrintModel.Printeds.Add(meters[0]);
                PrintModel.Unprinteds.Remove(meters[0]);

                //上传数据
                PrintRecordList printRecordList = new PrintRecordList();
                if (button.Tag.ToString() == "StrCanvas" || button.Tag.ToString() == "AllStrCanvas")
                {
                    printRecordList.SetSqlData(PrintModel, PrintCanvasModels, new ObservableCollection<PrintCanvasModel>());
                }

                if (button.Tag.ToString() == "BackCanvas" || button.Tag.ToString() == "AllBackCanvas")
                {
                    printRecordList.SetSqlData(PrintModel, new ObservableCollection<PrintCanvasModel>(), PrintBackCanvasModels);
                }

            }

            HandyControl.Controls.Growl.Info("打印完成！");

        }

        /// <summary>
        /// 新增项目行
        /// </summary>
        private void AddDataGridButton()
        {
            //先确认正反面，再确认哪个DataGrid 再输入哪一行，执行插入
            //案例：反面 DataGrid 编号 26 

            if(SelectedDataGrid == null)
            {
                HandyControl.Controls.Growl.Info("请先选择添加表格编号！");
                return;
            }

            if (IsBack)
            {
                InsertionIndex = GetInsertionIndex(PrintBackCanvasModels, SelectedDataGrid.ProjectId, InsertionIndex);
            }
            else
            {
                InsertionIndex = GetInsertionIndex(PrintCanvasModels, SelectedDataGrid.ProjectId, InsertionIndex);
            }
        }

        /// <summary>
        /// 双击列表根据现在临时模板重新修改内容参数
        /// 参数根据模板中是否变更值来判断是否变更
        /// </summary>
        /// <param name="meter">标定信息对象</param>
        private void CommandListViewItemClick(Meter meter)
        {
            PrintModel.SelectedListViewItem = meter;

            //映射框架
            PrintCanvasModels = GetPrintCanvasModels(PrintCanvasModels, meter, PrintModel.TaskInfo, PrintModel.SelectedPrintType, FirstIteration);

            if (IsTowSided)
            {
                PrintBackCanvasModels = GetPrintCanvasModels(PrintBackCanvasModels, meter, PrintModel.TaskInfo, PrintModel.SelectedPrintType, FirstIteration);
            }

        }

        /// <summary>
        /// 从数据集合中删除该数据项
        /// </summary>
        /// <param name="row"></param>
        private void CommandDataGridRowDelete(DataGridRow row)
        {
            if (row != null && row.DataContext is ContentEntries dataItem)
            {
                foreach (PrintCanvasModel item in PrintCanvasModels.Where(x => x.ProjectId == (int)row.Tag))
                {
                    item.DataGridLists.Remove(dataItem);
                    item.RowHeight = item.GetRowHeight();
                    if (!IsBack)
                    {
                        InsertionIndex = item.DataGridLists.Count;
                    }
                }

                foreach (PrintCanvasModel item in PrintBackCanvasModels.Where(x => x.ProjectId == (int)row.Tag))
                {
                    item.DataGridLists.Remove(dataItem);
                    item.RowHeight = item.GetRowHeight();
                    if (IsBack)
                    {
                        InsertionIndex = item.DataGridLists.Count;
                    }
                }
            }
        }

        /// <summary>
        /// 选择模板，自动加载默认打印机
        /// </summary>
        private void CommandDropDownClosed()
        {
            if (PrintModel.SelectedPrintType == null)
            {
                HandyControl.Controls.Growl.Warning("请选择模板！");
                return;
            }

            //选择默认打印机，如果找不到打印机，则提示
            PrintModel.SelectedPrinter = null;

            foreach (PrintQueue item in PrintModel.PrintQueues)
            {
                if (item.Name == PrintModel.SelectedPrintType.PrinterName)
                {
                    PrintModel.SelectedPrinter = item;
                    PrintDialog.PrintQueue = item;
                }
            }

            if (PrintModel.SelectedPrinter == null)
            {
                HandyControl.Controls.Growl.Warning("没有找到默认打印机！");
            }
        }

        /// <summary>
        /// 下拉框显示框架模板
        /// </summary>
        private void CommandDropDownOpened()
        {
            PrintTypes = _fsql.Select<PrintModelType>().ToList();
            PrintCanvasModels = new ObservableCollection<PrintCanvasModel>();
            PrintBackCanvasModels = new ObservableCollection<PrintCanvasModel>();
        }

        /// <summary>
        /// 任务单输入框键盘按下事件
        /// 1、确认选择模板
        /// 2、格式任务单号
        /// 3、判断数据源
        /// 4、读取任务信息，映射打印模板任务参数
        /// 5、判断标定信息
        /// 6、判断是否显示追溯码
        /// 7、判断内容模板
        /// 8、映射内容模板任务参数 
        /// </summary>
        private void SearchBarEnterKeyPressed(TextBox textBox)
        {
            // 处理按下回车键的逻辑，参数text为TextBox中的文本内容
            if (Keyboard.IsKeyDown(Key.Return))
            {
                if (PrintModel.SelectedPrintType == null)
                {
                    HandyControl.Controls.Growl.Warning("请选择模板！");
                    return;
                }

                //任务单号格式化
                if (!(textBox.Text ?? "WORK").StartsWith("WORK"))
                {
                    textBox.Text = textBox.Text.Length >= 6 ? textBox.Text.Substring(textBox.Text.Length - 6) : textBox.Text.PadLeft(6, '0');
                    PrintModel.Tisk = "WORK" + textBox.Text;
                }
                else
                {
                    PrintModel.Tisk = textBox.Text;
                }

                //判断数据源
                string source = "MeterTan";

                //获取任务单关联信息
                PrintModel.TaskInfo = _fsql.Ado.QuerySingle<TaskInfo>("SELECT * FROM TaskInfoTan WHERE FBillNo = @FBillNo ", new { FBillNo = PrintModel.Tisk });

                if (PrintModel.DataSource == false)
                {
                    source = "Meter";
                    PrintModel.TaskInfo = _fsql.Select<TaskInfo>().Where(a => a.FBillNo == PrintModel.Tisk).ToOne();
                }                

                if (PrintModel.TaskInfo == null)
                {
                    HandyControl.Controls.Growl.Warning("请确认任务单号！");
                    return;
                }

                //获取未打印出厂编号
                PrintModel.TaskInfo.Meters = _fsql.Ado.Query<Meter>("SELECT * FROM " + source + " WHERE TaskNumber = @TaskNumber ORDER BY FactoryNo ", new { TaskNumber = PrintModel.Tisk });
                PrintModel.Unprinteds = new ObservableCollection<Meter>(PrintModel.TaskInfo.Meters);

                //清除已打印列表
                PrintModel.Printeds.Clear();

                //未找到标定数据
                if (PrintModel.Unprinteds.Count == 0)
                {
                    //判断是否需要标定
                    bool IsVerification = _fsql.Ado.QuerySingle<bool>("SELECT JJGID FROM ais20160331162100.dbo.t_BOS200000005Entry2 WHERE FNumber = @FNumber", new { FNumber = PrintModel.TaskInfo.FNumber.Substring(2,2)});
                    
                    if (IsVerification)
                    {
                        //如果需要标定
                        HandyControl.Controls.Growl.Info("此任务单无标定数据！");
                        return;
                    }

                    //提示是否需要生成出厂编号
                    if (HandyControl.Controls.MessageBox.Ask("此任务单无绑定出厂编号，是否自动生成？", "询问提示") == MessageBoxResult.No)
                    {
                        return;
                    }

                    //自动填充出厂编号
                    string str = "DECLARE @retVal INT;EXEC @retVal = ais20160331162100.dbo.ADDFactoryNo  '" + PrintModel.Tisk + "';SELECT @retVal as 'Return';";
                    int num = _fsql.Ado.QuerySingle<int>(str);

                    HandyControl.Controls.MessageBox.Success("出厂编号添加成功！","通知");
                    //重新获取未打印出厂编号
                    PrintModel.TaskInfo.Meters = _fsql.Ado.Query<Meter>("SELECT * FROM " + source + " WHERE TaskNumber = @TaskNumber ", new { TaskNumber = PrintModel.Tisk });
                    PrintModel.Unprinteds = new ObservableCollection<Meter>(PrintModel.TaskInfo.Meters);

                }

                //加载正面框架模板
                List<PrintCanvasModel> list = _fsql.Select<PrintCanvasModel>()
                                                    .Where(a => a.ModelId == PrintModel.SelectedPrintType.Id)
                                                    .Where(a => a.IsReverse == false)
                                                    .OrderBy(a => a.OrderNo)
                                                    .ToList();
                PrintCanvasModels = new ObservableCollection<PrintCanvasModel>(list);

                //初始化反面
                PrintBackCanvasModels = new ObservableCollection<PrintCanvasModel>();

                //判断是否有反面
                IsTowSided = PrintModel.SelectedPrintType.IsTwoSided(PrintModel.TaskInfo);

                if (IsTowSided)
                {
                    list = _fsql.Select<PrintCanvasModel>()
                    .Where(a => a.ModelId == PrintModel.SelectedPrintType.Id)
                    .Where(a => a.IsReverse == true)
                    .OrderBy(a => a.OrderNo)
                    .ToList();
                    PrintBackCanvasModels = new ObservableCollection<PrintCanvasModel>(list);
                }

                //判断此任务单是否显示追溯码
                if (PrintModel.Unprinteds[0].ENNTraceCode == null)
                {
                    foreach (PrintCanvasModel item in PrintCanvasModels.Where(x => x.ControlType == "ENNQRCode"))
                    {
                        item.IsdisplayKeyword = false;
                    }
                }
                else
                {
                    foreach (PrintCanvasModel item in PrintCanvasModels.Where(x => x.ControlType == "ENNQRCode"))
                    {
                        item.IsdisplayKeyword = true;
                    }
                }

                //设置为第一次
                FirstIteration = true;
                CommandListViewItemClick(PrintModel.Unprinteds[0]);
                FirstIteration = false;

                foreach (PrintCanvasModel item in PrintCanvasModels.Where(x => x.ControlType == "DataGrid"))
                {
                    SelectedDataGrid = item;
                    break;
                }
                InsertionIndex = SelectedDataGrid.DataGridLists.Count;

                //设置DataGrid宽度
                DataGridWidth(PrintCanvasModels);
                DataGridWidth(PrintBackCanvasModels);

            }
        }

        /// <summary>
        /// Helper方法：在视觉树中查找指定名称的元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parent">视觉树对象</param>
        /// <param name="name">元素名称</param>
        /// <returns>元素对象</returns>
        public static T FindVisualChild<T>(DependencyObject parent, string name) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);

                if (child is T element && (element as FrameworkElement)?.Name == name)
                {
                    return element;
                }

                T result = FindVisualChild<T>(child, name);

                if (result != null)
                {
                    return result;
                }
            }

            return null;
        }

        #region 穿梭框

        /// <summary>
        /// 全部右移
        /// </summary>
        private void CommandAllRightButton()
        {
            foreach (Meter meter in PrintModel.Printeds)
            {
                PrintModel.Unprinteds.Add(meter);
            }

            PrintModel.Printeds.Clear();
        }

        /// <summary>
        /// 右移
        /// </summary>
        private void CommandRightButton()
        {
            ListView PrintedsSelect = FindVisualChild<ListView>(App.Current.MainWindow, "Printed");

            List<Meter> meters = new List<Meter>();
            foreach (Meter item in PrintedsSelect.SelectedItems)
            {
                meters.Add(item);
            }

            foreach (Meter meter in meters)
            {
                PrintModel.Unprinteds.Add(meter);
                PrintModel.Printeds.Remove(meter);
            }
        }

        /// <summary>
        /// 左移
        /// </summary>
        private void CommandLeftButton()
        {
            ListView UnprintedsSelect = FindVisualChild<ListView>(App.Current.MainWindow, "Unprinted");

            List<Meter> meters = new List<Meter>();
            foreach (Meter item in UnprintedsSelect.SelectedItems)
            {
                meters.Add(item);
            }

            foreach (Meter meter in meters)
            {
                PrintModel.Printeds.Add(meter);
                PrintModel.Unprinteds.Remove(meter);
            }
        }

        /// <summary>
        /// 全部左移
        /// </summary>
        private void CommandAllLeftButton()
        {
            foreach (Meter meter in PrintModel.Unprinteds)
            {
                PrintModel.Printeds.Add(meter);
            }

            PrintModel.Unprinteds.Clear();

        }

        #endregion

        /// <summary>
        /// 加载并映射模板信息
        /// </summary>
        /// <param name="printCanvasModels">模板类型页面明细</param>
        /// <param name="meter">标定信息</param>
        /// <param name="taskInfo">任务信息</param>
        /// <param name="contentType">页面表格</param>
        /// <param name="firstIteration">此任务单第一次加载标志</param>
        /// <returns></returns>
        public ObservableCollection<PrintCanvasModel> GetPrintCanvasModels(ObservableCollection<PrintCanvasModel> printCanvasModels, Meter meter, TaskInfo taskInfo,PrintModelType printModelType , bool firstIteration)
        {
            foreach (PrintCanvasModel item in printCanvasModels)
            {
                if (item.TaskChange || item.MeterChange || firstIteration)
                {
                    //任务信息
                    object propertyValue = typeof(TaskInfo).GetProperty(item.ProjectName)?.GetValue(taskInfo, null);

                    if(propertyValue == null)
                    {
                        //标定参数
                        propertyValue = typeof(Meter).GetProperty(item.ProjectName)?.GetValue(meter, null);
                    }

                    // 使用模式匹配检查属性值是否为 null，并设置 Contents
                    item.Contents = propertyValue is null ? item.Contents : propertyValue.ToString();
                }

                if (item.ControlType == "DataGrid") 
                {
                    if (firstIteration)
                    {
                        //加载表格模板映射
                        ContentTemplateMapping mapping = printModelType.GetContentTemplateMapping(taskInfo,item.ProjectId);

                        //加载表格模板
                        item.ContentType = _fsql.Select<ContentType>().Where(a => a.ContentModelId == mapping.ContentModelId).ToOne();

                        List<ContentEntries> contentEntries = _fsql.Select<ContentEntries>()
                                                                    .Where(a => a.ContentModelId == item.ContentType.ContentModelId)
                                                                    .OrderBy(a => a.OrderNo)
                                                                    .ToList();
                        item.DataGridLists = new ObservableCollection<ContentEntries>(contentEntries);
                    }

                    //映射数据
                    item.DataGridLists = item.GetDataGridLists(meter, taskInfo, firstIteration);
                }

            }

            return printCanvasModels;
        }

        public int GetInsertionIndex(ObservableCollection<PrintCanvasModel> printCanvasModels,int projectid,int insertionIndex)
        {
            foreach (PrintCanvasModel item in printCanvasModels.Where(x => x.ProjectId == projectid))
            {
                item.DataGridLists.Insert(insertionIndex, new ContentEntries() { ContentName = "项目名称", AttriName = "项目内容" });

                item.RowHeight = item.GetRowHeight();

                return item.DataGridLists.Count;
            }
            return 0;
        }

        public static List<T> FindVisualChildren<T>(DependencyObject parent, string name) where T : DependencyObject
        {
            List<T> elements = new List<T>();

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);

                if (child is T element && (element as FrameworkElement)?.Name == name)
                {
                    elements.Add(element);
                }

                List<T> results = FindVisualChildren<T>(child, name);
                elements.AddRange(results);
            }

            return elements;
        }

        public static void DataGridWidth(ObservableCollection<PrintCanvasModel> printCanvasModels)
        {
            //Border border = FindVisualChild<Border>(App.Current.MainWindow, str);

            //手动刷新 Canvas UI
            App.Current.MainWindow.UpdateLayout();

            List<DataGrid> dataGrids = FindVisualChildren<DataGrid>(App.Current.MainWindow, "DataGridCanvas");

            foreach (DataGrid dataGrid in dataGrids)
            {
                if (dataGrid != null && dataGrid.DataContext is PrintCanvasModel canvas)
                {
                    dataGrid.Columns[0].Width = canvas.ContentType.FirstColumnWidth;
                    dataGrid.Columns[1].Width = canvas.ContentType.SecondColumnWidth;
                }
            }


            foreach (PrintCanvasModel item in printCanvasModels.Where(x => x.ControlType == "DataGrid"))
            {
                //设置行高
                item.RowHeight = item.GetRowHeight();
            }
        }

    }
}
